import WebSocketConnectMethod from '@/assets/js/wsconnecter';


export default {
  initWebSocket(options) {
    try {
      const wsconnecter = new WebSocketConnectMethod({
        file: options.file,
        stateHandle: options.stateHandle,
        msgHandle: options.msgHandle,
        use_itn: options.use_itn,
        asr_mode: options.asr_mode,
        isfilemode: options.isfilemode,
        hotwords: JSON.stringify(options.hotwords)
      });
      console.log('wsconnecter 初始化成功:', wsconnecter);
      return wsconnecter;
    } catch (error) {
      console.error('wsconnecter 初始化失败:', error);
      throw new Error('初始化失败');
    }
  },

  handleWithTimestamp(tmptext, tmptime) { // 处理带时间戳的文本
    console.log("tmptext: " + tmptext);
    // console.log("tmptime: " + tmptime);
    if (tmptime == null || tmptime == "undefined" || tmptext.length <= 0) {
      return tmptext;
    }
    tmptext = tmptext.replace(/。|？|，|、|\?|\.|\ /g, ","); // in case there are a lot of "。"
    var words = tmptext.split(",");  // split to chinese sentence or english words
    var jsontime;
    // if(tmptime){
    //   jsontime = JSON.parse(tmptime); //JSON.parse(tmptime.replace(/\]\]\[\[/g, "],[")); // in case there are a lot segments by VAD
    // }
    var char_index = 0; // index for timestamp
    var text_withtime = "";
    for (var i = 0; i < words.length; i++) {
      if (words[i] == "undefined" || words[i].length <= 0) {
        continue;
      }
      // console.log("words===", words[i]);
      // console.log("words: " + words[i] + ",time=" + jsontime[char_index][0] / 1000);
      if (/^[a-zA-Z]+$/.test(words[i])) {   // if it is english
        text_withtime = text_withtime + words[i] + "\n";
        char_index = char_index + 1;  //for english, timestamp unit is about a word
      }
      else {
        // if it is chinese
        text_withtime = text_withtime + jsontime[char_index][0] / 1000 + ":" + words[i] + "\n";
        char_index = char_index + words[i].length; //for chinese, timestamp unit is about a char
      }
    }
    return text_withtime;
  }
};